<template>
    <div class="interface_block">
        <div class="top">
            <search-bar v-model="searchModel" :search-data="searchData" :config="searchData" @search="handleSearchSubmit"
                @searchReset="handleSearchReset" style="margin-top:0;margin-left:-20px;padding-top:.2rem">
            </search-bar>
        </div>
        <div class="bottom">
            <div class="btn_area">

                <el-button plain @click="deleteCustomer" size="medium"
                    >重新调用</el-button>
                <el-button type="primary" @click="allot" size="medium"
                  >清理</el-button>


            </div>

            <LPTablePage :show-index="false" :table-data="tableData" :table-column="tableColumn" :total="total"
                :current-page="currentPage" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"
                :selection="true" @handleSelectionChange="handleSelectionChange" ref="tablePage" :selectable="selectable"
                :height="'calc(100vh - 324px -  .84rem)'">
                <template slot="customerName" slot-scope="{row}">
                    <span>{{ row.region ? row.customerName + `(${(row.region)})` : row.customerName }}</span>
                </template>

                <template slot="followUpStatus" slot-scope="{row}">
                    <span v-if="row.followUpStatus == '初步沟通'" class="green">
                        {{ row.followUpStatus }}
                    </span>
                    <span v-else-if="row.followUpStatus == '合同沟通'" class="blue">
                        {{ row.followUpStatus }}
                    </span>
                    <span v-else-if="row.followUpStatus == '意向下单'" class="orage">
                        {{ row.followUpStatus }}
                    </span>
                    <span v-else-if="row.followUpStatus == '达成合作'" class="red">
                        {{ row.followUpStatus }}
                    </span>
                    <span v-else>
                        {{ row.followUpStatus }}
                    </span>
                </template>

                <template slot="tags" slot-scope="{row}">
                    <div v-html="gethtml(row.tags)"></div>
                </template>

            </LPTablePage>

        

            <!-- 详情页 -->
            <!-- <openSeaDetail 
                :visible="detailVisible"
                @handleDialogClose="detailClose"
                @handleAllot="handleAllot"
                ref="openSeaDetail"
                :userOptions="userOptions"
                :openSeaClueId="openSeaClueId"
                :status="status"
                :isCanTakeAudit="isCanTakeAudit"
                /> -->

        </div>
    </div>
</template>

<script>
import { validateNumber } from "@/utils/validate";
import baseDialog from '@/components/BaseDialog'
import SearchBar from '@/components/SearchBar'
import LPTablePage from '@/components/LPTablePage'
// import TablePage from '@/components/TablePage'

// import {
// getOpenSeaList,
// getOpenSeaSetting,
// putOpenSeaStting,
// allotOpenSea,
// takeOpenSea,
// deleteOpenSea
// } from '@/api/openSea'

// import {auditSuccess,auditReject} from "@/api/customer";


export default {
    name: "Interface",
    components: {
        LPTablePage, SearchBar, baseDialog
    },
    data() {
        const validateNumberF = (rule, value, callback) => {
            if (Number(value) == 0) {
                return callback(new Error("不能为0"));
            }
            if (!validateNumber(value)) {
                return callback(new Error("请输入正确数字"));
            } else {
                callback();
            }
        };
        const validateEmpty = (rule, value, callback) => {
            console.log('validateEmpty', value, value instanceof Array);
            if (!(value instanceof Array)) {
                return callback(new Error("必填"));
            }
            if (value instanceof Array && value.length == 0) {
                return callback(new Error("必填"));
            } else {
                callback()
            }
        };
        return {
            searchModel: {},
            searchData: [

                {
                    prop: 'systemType',
                    type: 'select',
                    placeholder: '所属系统',
                    options: [
                        { label: 'CRM', value: '1' },
                        { label: '劳保', value: '2' },

                    ]
                },

                {
                    label: "日期", prop: "CreationTime", type: "datetimerange",
                    startPlaceholder: "起始时间",
                    endPlaceholder: "结束时间",
                    span: 6
                },

            ],
            tableData: [],
            tableColumn: [
                { label: "访问编号", prop: "code", },
                { label: "接口类型", prop: "customerName" },
                { label: "调用方法", prop: "customerName" },

                { label: "状态", prop: "status", },
                { label: "错误信息", prop: "address", },
                { label: "对象ID", prop: "place", },

                { label: "创建时间", prop: "createTime", },



                //  {
                //     label: "操作",
                //     prop: "action",
                //     type: "button",
                //     hideTooLtip:true,
                //     width:180,
                //     button:[
                //         {
                //             label: "查看",
                //             type: "text",
                //             icon: "el-icon-view",
                //             method:`_detail${this.$options.name}`
                //         },
                //         {
                //             label: "通过",
                //             type: "text",
                //             icon: "el-icon-view",
                //             hide:'isCanTakeAudit',
                //             // hide:'canTakeAudit',
                //             hideValue:[false],
                //             policy:['Crm.CluePoolManage.TakeAudit'],
                //             method:`_auditSuccess${this.$options.name}`
                //         },
                //         {
                //             label: "驳回",
                //             type: "text",
                //             icon: "el-icon-view",
                //             hide:'isCanTakeAudit',
                //             // hide:'canTakeAudit',
                //             hideValue:[false],
                //             policy:['Crm.CluePoolManage.TakeAudit'],
                //             method:`_auditFail${this.$options.name}`
                //         },
                //     ]
                //  }   
            ],
            total: 0,
            currentPage: 1,
            selectArr: [],
            allotVisile: false,
            allotModel: {},
            allotRule: {
                responsibleUserId: [
                    // { required: true, trigger: "blur", message: "必填" },
                    { validator: validateEmpty, required: true, trigger: "blur" }
                ],
            },
            userOptions: [],
            settingVisile: false,
            ruleModel: {},
            ruleRule: {
                autoRecycleEnable: [{ required: true, trigger: "blur", message: "必填" }],
                autoRecycleByNotFollowUpOverDays: [{ required: true, trigger: "blur", message: "必填" },
                { validator: validateNumberF, required: true, trigger: "blur" }],

                originalResponsibleUserTakeLimit: [{ required: true, trigger: "blur", message: "必填" }],
                originalResponsibleUserTakeLimitDays: [{ required: true, trigger: "blur", message: "必填" },
                { validator: validateNumberF, required: true, trigger: "blur" },
                ],
                takeLimit: [{ required: true, trigger: "blur", message: "必填" }],
                takeLimitByEveryDayNumbers: [{ required: true, trigger: "blur", message: "必填" },
                { validator: validateNumberF, required: true, trigger: "blur" },
                ],
            },
            detailVisible: false,
            detailId: '',
            openSeaClueId: '',
            status: null,
            isCanTakeAudit: null
        }
    },
    mounted() {
        // this.handTableEvents()
        // this.getOpenSeaList()
        // this.initDropdown()
    },
    methods: {
        handTableEvents() {
            this.tableBus.$on(`_detail${this.$options.name}`, (row) => {
                console.log("查看", row);
                this.detailId = row.customerClueId;
                this.openSeaClueId = row.id;
                this.status = row.status;
                this.isCanTakeAudit = row.isCanTakeAudit;
                this.detailVisible = true;
                this.$refs.openSeaDetail.getOpenSeaDetailById(row.customerClueId)
                //  this.followModel = {...row}
            });
            this.tableBus.$on(`_auditSuccess${this.$options.name}`, (row) => {
                console.log('审核通过', row);
                let data = {
                    category: 3,
                    id: row.id
                }
                auditSuccess(data).then(res => {
                    if (!res.error) {
                        this.$message.success('操作成功');
                        this.getOpenSeaList()
                    }
                })

            });
            this.tableBus.$on(`_auditFail${this.$options.name}`, (row) => {
                console.log('审核驳回', row);
                let data = {
                    category: 3,
                    id: row.id
                }
                auditReject(data).then(res => {
                    if (!res.error) {
                        this.$message.success('操作成功');
                        this.getOpenSeaList()
                    }
                })

            });
        },
        getOpenSeaList() {
            let { pageSize } = this.$refs.tablePage;
            let params = {
                ...this.searchModel,
                MaxResultCount: pageSize,
                SkipCount: (this.currentPage - 1) * pageSize,
                BeginFollowUpTime: this.searchModel.FollowUpTime ? this.searchModel.FollowUpTime[0] : null,
                EndFollowUpTime: this.searchModel.FollowUpTime ? this.searchModel.FollowUpTime[1] : null,
                BeginCreationTime: this.searchModel.CreationTime ? this.searchModel.CreationTime[0] : null,
                EndCreationTime: this.searchModel.CreationTime ? this.searchModel.CreationTime[1] : null,
            }
            if (params.customerTypesArr && params.customerTypesArr.length > 0) {
                params.customerTypes = params.customerTypesArr.join(',');
            }
            if (!params.CustomerTypes) delete params.CustomerTypes;
            if (!params.Sources) delete params.Sources;
            getOpenSeaList(params).then(res => {
                if (!res.error) {
                    console.log('getOpenSeaList', res);
                    this.total = res.totalCount;
                    this.tableData = res.items
                    // .map(item => {
                    //     return {
                    //         ...item,
                    //         // 审核按钮
                    //         canTakeAudit: (item.isCanTakeAudit && item.status == 1) || false
                    //     }
                    // });
                }
            })
        },
        selectable(row, index) {
            if (row.status == 0) {
                return true
            } else {
                return false
            }
        },
        handleSearchSubmit() {
            this.currentPage = 1;
            this.getOpenSeaList()
        },
        handleSearchReset() {
            this.currentPage = 1;
            this.$refs.tablePage.clearSelection()
            this.getOpenSeaList()
        },
        handleSizeChange(v) {
            this.pageSize = v;
            this.currentPage = 1;
            this.getOpenSeaList()
        },
        handleCurrentChange(v) {
            this.currentPage = v;
            this.getOpenSeaList()
        },
        handleSelectionChange(v) {
            console.log('handleSelectionChange', v);
            this.selectArr = v
        },
        allot() {
            if (this.selectArr.length == 0) {
                this.$message.warning("请先勾选客户")
                return
            }
            this.allotVisile = true;
        },
        handleAllotSubmit() {
            this.$refs.allotForm.validate(valid => {
                if (valid) {
                    let params = {
                        ids: this.selectArr.map(item => item.id),
                        responsibleUserId: this.allotModel.responsibleUserId[this.allotModel.responsibleUserId.length - 1],
                        responsibleUserName: this.$refs['cascaderAddr'].getCheckedNodes()[0].label
                    }
                    allotOpenSea(params).then(res => {
                        if (!res.error) {
                            this.$message.success("分配成功")
                            this.allotVisile = false;
                            this.getOpenSeaList()
                            this.$refs.tablePage.clearSelection()
                        }
                    })
                } else {
                    return false
                }
            })
        },
        handleAllotCancle() {
            this.allotVisile = false;
            this.resetForm("allotForm")
            this.allotModel = {}
        },
        getCustomer() {
            if (this.selectArr.length == 0) {
                this.$message.warning("请先勾选客户")
                return
            }
            if (this.selectArr.length != 1) {
                this.$message.warning("仅支持单个客户领取")
                return
            }
            this.$confirm('确定领取该客户?', '领取', {
                cancelButtonText: '取消',
                confirmButtonText: '确定',
                closeOnClickModal: false
            }).then(() => {
                //   console.log('确认');
                let params = {
                    ids: this.selectArr.map(item => item.id),
                }
                takeOpenSea(params).then(res => {
                    if (!res.error) {
                        console.log('takeOpenSea', res);
                        this.$message.success("提交领取审核成功")
                        this.getOpenSeaList()
                        this.$refs.tablePage.clearSelection()
                    }
                })
            })
        },
        deleteCustomer() {
            if (this.selectArr.length == 0) {
                this.$message.warning("请先勾选客户")
                return
            }
            this.$confirm('确定删除吗', '删除', {
                cancelButtonText: '取消',
                confirmButtonText: '确定',
                closeOnClickModal: false
            }).then(() => {
                //   console.log('确认');
                let params = {
                    ids: this.selectArr.map(item => item.id),
                }
                deleteOpenSea(params).then(res => {
                    if (!res.error) {
                        this.$message.success("操作成功")
                        this.getOpenSeaList()
                        this.$refs.tablePage.clearSelection()
                    }
                })
            })
        },
        gethtml(value) {
            if (value == null) {
                return;
            }
            var list = value.split(',');
            var resultStr = ""
            list.forEach(item => {
                if (item.includes("高") || item.includes("重要")) {
                    resultStr = resultStr + "<span style='color:#EE3333'>" + item + "</span>,";
                }
                else {
                    resultStr = resultStr + item + ",";
                }
            })
            if (resultStr != "") {
                return resultStr.slice(0, -1);
            }
        },
        showSettign() {
            getOpenSeaSetting().then(res => {
                if (!res.error) {
                    console.log('getOpenSeaSetting', res);
                    this.ruleModel = res;
                    this.settingVisile = true;
                }
            })
        },
        handleSettingSubmit() {
            this.$refs.ruleForm.validate(valid => {
                if (valid) {
                    console.log('ruleModel', this.ruleModel);
                    putOpenSeaStting(this.ruleModel).then(res => {
                        if (!res.error) {
                            this.$message.success("保存设置成功")
                            this.settingVisile = false;
                        }
                    })
                } else {
                    return false
                }
            })
        },
        handleSettingCancle() {
            this.settingVisile = false;
        },
        detailClose() {
            this.detailVisible = false;
            this.getOpenSeaList()
        },
        handleAllot() {
            this.allotVisile = true;
        },
        async initDropdown() {
            let Sources = await this.$store.dispatch('dict/getCustomerSources')
            this.searchData.find(v => v.prop === 'Sources').option = Sources;
            let customerType = await this.$store.dispatch('dict/getCustomerTypes')
            this.searchData.find(v => v.prop === 'customerTypesArr').option = customerType;
            let userOptions = await this.$store.dispatch("common/getUserORGTree")
            // this.userOptions = userOptions;
            this.userOptions = userOptions.map(item => {
                return this.disableUser(item)
            });
        },
        disableUser(opt) {
            if (opt.children && opt.children.length != 0) {
                opt.children = opt.children.map(item => {
                    return this.disableUser(item)
                })
                return opt
            } else {
                if (opt.data.type == 'org') {
                    opt.disabled = true
                }
                return opt
            }
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
    }
}
</script>

<style lang="scss" scoped>
.interface_block {

    // padding: 0 .2rem .2rem;
    .top {
        background-color: #fff;
        padding: 0 .3rem;
    }

    .bottom {
        .btn_area {
            margin-bottom: .2rem;
            margin-left: .3rem;
            margin-right: .3rem;

            .settingBtn {
                float: right;
            }
        }

        background-color: #fff;
        margin-top: .2rem;
        padding: .2rem 0rem;
    }
    .green {
        color: #2CAD00;
    }

    .orage {
        color: #EE7533;
    }

    .blue {
        color: #0076FF;
    }

    .red {
        color: #ff3333;
    }
}
</style>